/**
 * Created by cchen on 2015/5/19.
 */
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}
if (!String.prototype.format) {
    String.prototype.format = function () {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function (match, number) {
            return typeof args[number] != 'undefined'
                ? args[number]
                : match;
        });
    };
}
String.prototype.replaceAll = function (oldStr, newStr) {
    return this.replace(new RegExp(oldStr, 'g'), newStr);
}

'use strict';
angular.module('backofficeApp.BDMarketingManager.controller', []).
    controller('commAppsCtrl', ['$scope', '$http', function ($scope, $http) {
        $scope.date = new Date()

        $scope.communityList = []

        $scope.commAppsData = []

        $scope.getCommAppsData = function (comm, start, end) {
            var community = !comm ? 'all' : comm
            var startDate = !start ? 'all' : start
            var endDate = !end ? 'all' : end

            $('#loadingText').html('Loading...')
            if (startDate === 'all')
                $('#startDateText').html('开始')
            else
                $('#startDateText').html(startDate)
            if (endDate === 'all')
                $('#endDateText').html(new Date().format('yyyy-MM-dd hh:mm:ss'))
            else
                $('#endDateText').html(endDate)

            $scope.commAppsData = []
            getCommAppsDataAPI(community, startDate, endDate)

        }

        function getCommAppsDataAPI(community, startDate, endDate) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/BI/reports/getCommApps/' + community + '/' + startDate + '/' + endDate, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.commAppsData = data.data
                $('#loadingText').html('')
            }).error(function () {
            });
        }

        function initPage() {
            function getCommListAPI() {
                $http.get('http://' + backOfficeHost + '/rest/v1.0/communities/getAllCommunityFromSQL', {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    var len = data.data.length
                    for (var i = 0; i < len; i++) {
                        if (data.data[i].isValid == 'True')
                            $scope.communityList.push(data.data[i])
                    }
                }).error(function () {
                });
            }

            getCommListAPI()
            getCommAppsDataAPI('all', 'all', 'all')
        }

        initPage()

        // Sort columns
        $scope.orderByField = 'communityName';
        $scope.reverseSort = true;
    }]).
    controller('inviteListCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.communityList = []

        $scope.communityNames = {}

        function getCommListAPI() {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/communities/getAllCommunityFromSQL', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var len = data.data.length
                for (var i = 0; i < len; i++) {
                    if (data.data[i].isValid == 'True'){
                        var item = data.data[i]
                        $scope.communityList.push(item)
                        $scope.communityNames[item['objId']] = item['communityName']
                    }
                }
            }).error(function () {
            });
        }

        getCommListAPI()

        var allCommName = '全部'

        function getCommunityName(commId) {
            if (commId == 'all')
                return allCommName
            var commName = ''
            var len = $scope.communityList.length;
            for (var i = 0; i < len; i++) {
                if ($scope.communityList[i].objId == commId) {
                    commName = $scope.communityList[i].communityName
                    break
                }
            }
            return commName
        }

        $scope.inviteList = []
        $scope.inviteSentList = []

        $scope.refreshInviteList = function (community) {
            getinviteListAPI(community)
        }

        var inviteSentPageLoaded = false;

        $scope.initInviteSentList = function (community) {
            if (!inviteSentPageLoaded)
                getInviteSentListAPI(community)
            inviteSentPageLoaded = true
        }
        $scope.refreshInviteSentList = function (community) {
            getInviteSentListAPI(community)
        }

        $scope.exportInviteListData = function () {
            var blob = new Blob([document.getElementById('exportable1').innerHTML], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
            });
            saveAs(blob, "InviteList.xls");
        }


        function getinviteListAPI(community) {
            $('#loadingInviteText').html("Loading...")

            if (!community)
                community = 'all'

            //$scope.inviteList = []
            $http.get('http://' + backOfficeHost + '/rest/v1.0/BI/reports/getMarketingInviteList/' + community, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                data.data.forEach(function(item){
                    item['inviterCommName'] = $scope.communityNames[item['inviterComm']]
                    item['inviteeCommName'] = $scope.communityNames[item['inviteeComm']]
                    $scope.inviteList.push(item)
                })
                $scope.inviteList = data.data
                $('#loadingInviteText').html('')
            }).error(function () {
            });
        }

        getinviteListAPI('all')

        $scope.orderByField = 'dc';
        $scope.reverseSort = true;

        function getInviteSentListAPI(community) {
            $('#loadingInviteSentText').html("Loading...")

            if (!community)
                community = 'all'

            //$scope.inviteSentList = []
            $http.get('http://' + backOfficeHost + '/rest/v1.0/BI/reports/getMarketingInviteSentList/' + community, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.inviteSentList = data.data
                $('#loadingInviteSentText').html('')
            }).error(function () {
            });
        }

        $scope.exportInviteSentListData = function () {
            var blob = new Blob([document.getElementById('exportable2').innerHTML], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
            });
            saveAs(blob, "InviteSentList.xls");
        }
        //getInviteSentListAPI('all')

        //$scope.printOut = function(){
        //    console.log($scope.communityList)
        //}

    }]).
    controller('promoCodeStatsCtrl', ['$scope', '$http', function ($scope, $http) {

        $scope.communityList = []

        function getCommListAPI() {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/communities/getAllCommunityFromSQL', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var len = data.data.length
                for (var i = 0; i < len; i++) {
                    if (data.data[i].isValid == 'True')
                        $scope.communityList.push(data.data[i])
                }
            }).error(function () {
            });
        }

        getCommListAPI()

        var allCommName = '全部'

        function getCommunityName(commId) {
            if (commId == 'all')
                return allCommName
            var commName = ''
            var len = $scope.communityList.length;
            for (var i = 0; i < len; i++) {
                if ($scope.communityList[i].objId == commId) {
                    commName = $scope.communityList[i].communityName
                    break
                }
            }
            return commName
        }

        $scope.promoCodeStats = {}      // {community1: {date}, community2: {}, ...}
        $scope.statsDisplay = {}

        $scope.community = null
        $scope.communityName = null

        $scope.getPromoCodeStats = function (community, startDate, endDate) {
            $('#loadingText').html('Loading...')

            $scope.statsDisplay = {}

            community = !community ? 'all' : community
            startDate = !startDate ? 'all' : startDate
            endDate = !endDate ? 'all' : endDate

            $scope.community = community
            $scope.communityName = getCommunityName(community)
            $scope.startDate = startDate
            $scope.endDate = endDate

            if (!$scope.promoCodeStats[community]) {
                var promise = getPromoCodeStatsAPI(community, startDate, endDate)
                promise.then(function (data) {
                    statsDisplay(community, startDate, endDate)
                    calcPromoCodeStatsTotal()
                    $('#loadingText').html('')
                })
            } else {
                statsDisplay(community, startDate, endDate)
                calcPromoCodeStatsTotal()
                $('#loadingText').html('')
            }
        }

        function statsDisplay(community, startDate, endDate) {
            if(startDate == 'all')
                startDate = '2000-01-01'
            if(endDate == 'all')
                endDate = new Date().format('yyyy-MM-dd 23:59:59')
            var cache = $scope.promoCodeStats[community]
            for (var date in cache) {
                if(date < startDate || date > endDate)
                    continue
                $scope.statsDisplay[date] = {}
                for (var type in cache[date]){
                    $scope.statsDisplay[date][type] = cache[date][type]
                }
            }
        }

        function calcPromoCodeStatsTotal() {
            var data = $scope.statsDisplay
            data['total'] = {total: 0}
            for (var date in data) {
                if (date == 'total')
                    continue
                for (var type in data[date]) {
                    if (!data['total'][type])
                        data['total'][type] = 0
                    if (!data[date]['total'])
                        data[date]['total'] = 0
                    data['total'][type] += data[date][type]
                    data['total']['total'] += data[date][type]
                    data[date]['total'] += data[date][type]
                }
            }
        }

        function getPromoCodeStatsAPI(community, startDate, endDate) {
            $scope.promoCodeStats[community] = {}
            var promise = $http.get('http://' + backOfficeHost + '/rest/v1.0/BI/reports/getPromoCodeStats/' + community + '/' + startDate + '/' + endDate, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).then(function (data) {
                var dt = data.data.data
                var cache = $scope.promoCodeStats[community]
                for (var type in dt) {
                    dt[type].forEach(function (item) {
                        var date = item.dc
                        var subType = item.auth == 'True' ? type + 'V' : type + 'NV'
                        if (!cache[date])
                            cache[date] = {}
                        cache[date][subType] = item.count
                    })
                }
            });
            return promise;
        }

        $scope.getPromoCodeStats('all', 'all', 'all')


        $scope.exportPromoCodeData = function () {
            var blob = new Blob([document.getElementById('exportable').innerHTML], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
            });
            saveAs(blob, "{0}_{1}-{2} PromoCodeStats.xls".format($scope.communityName, $scope.startDate.replaceAll('-', ''), $scope.endDate.replaceAll('-', '')));
        }

    }])